package com.cloud.force.api.provider;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.jdbc.SQL;

import com.cloud.force.api.bean.RecForceSearchCriteria;
import com.cloud.force.common.utils.DateHelper;

public class RecForceSearchPageProvider {
	private static final String LIST_PAGE_SELECT = "t1.rec_id, t1.task_num, DATE_FORMAT(t1.register_date,'%Y-%m-%d') as register_date, t1.rec_type_id, t1.rec_type_name, t1.event_src_id, t1.event_src_name, t1.domain_type_id, t1.domain_type_name,t1.unit_name, IF ( t2.litigant_type_id = '01', t2.person_name, t2.company_name ) AS litigant_name, GROUP_CONCAT(t3.cause_content) cause_content,CONCAT(IFNULL(t4.excute_doc_num,''),IFNULL(t5.approval_doc_num,'')) as forcesDocNum",
			LIST_PAGE_FOMR = "rec_force t1 LEFT JOIN rec_litigant_info t2 ON t1.rec_id = t2.rec_id LEFT JOIN rec_cause t3 ON t1.rec_id = t3.rec_id LEFT JOIN rec_force_execute t4 ON t1.rec_id = t4.rec_id LEFT JOIN rec_force_measure t5 ON t1.rec_id = t5.rec_id";

	public String listPage(RecForceSearchCriteria criteria) {
		SQL sql = new SQL().SELECT(LIST_PAGE_SELECT).FROM(LIST_PAGE_FOMR);
		// 区划过滤，只能查看平级或下级区划的案卷信息
		if(!StringUtils.isEmpty(criteria.getRegionCode())){
			sql.WHERE("t1.region_code like '"+ criteria.getRegionCode() +"%'"); 
		}
//		// 领域过滤只能查看管辖领域内的案卷
//		if(null != criteria.getDomains() && criteria.getDomains().size() > 0){
//			sql.WHERE("t1.domain_type_id in ("+ StringUtils.join(criteria.getDomains(), ",")+")");
//		}

		if (criteria.getUnitCode() != null) {
			sql.WHERE("t1.unit_code like  '" + criteria.getUnitCode() + "%" + "'");
		}
		// 任务号
		if (!StringUtils.isEmpty(criteria.getTaskNum())) {
			sql.WHERE("t1.task_num like '%" + criteria.getTaskNum() + "%'");
		}
		// 当事人姓名
		if (!StringUtils.isEmpty(criteria.getLitigantName())) {
			sql.WHERE("(t2.person_name like '%" + criteria.getLitigantName() + "%' or t2.company_name like '%"
					+ criteria.getLitigantName() + "%')");
		}
		// 案卷类型
		if (!StringUtils.isEmpty(criteria.getRecTypeId())) {
			sql.WHERE("t1.rec_type_id = '" + criteria.getRecTypeId() + "'");
		}
		// 案由
		if (!StringUtils.isEmpty(criteria.getCauseName())) {
			sql.WHERE("t3.cause_content like '%" + criteria.getCauseName() + "%'");
		}
		// 立案时间
		if (null != criteria.getRegisterDate()) {
			sql.WHERE("t1.register_date = " + DateHelper.strToDateSql(DateHelper.dateToStr(criteria.getRegisterDate()),
					0, DateHelper.DB_TYPE_MYSQL));
		}
		//强制决定书文号
		if (null != criteria.getForcesDocNum()) {
			sql.WHERE("t4.excute_doc_num like '%" + criteria.getForcesDocNum() + "%'" + "or" + " t5.approval_doc_num like '%"+ criteria.getForcesDocNum() + "%'");
		}
		//执法领域
		if (null != criteria.getDomainTypeName()) {
			sql.WHERE("t1.domain_type_name like '%" + criteria.getDomainTypeName() + "%'");
		}
		// 状态不是作废
		sql.WHERE("t1.state_id <> 99");
		sql.GROUP_BY("t1.rec_id");
		sql.ORDER_BY("t1.task_num desc");
		return sql.toString();
	}
}
